<?php


namespace app\api\middleware;

use app\common\controller\ApiBase;
use app\common\controller\Base;
use app\Constant\ApiConstant;
use thans\jwt\facade\JWTAuth;
use think\facade\Request;

/*
 * 请求前验证req_token
 */

/**
 * @method static auth()
 */
class TokenAuth extends ApiBase
{
    /**
     * @return mixed
     * @throws \Exception
     * @var \think\Request $request
     * @var mixed $next
     */
    public function handle($request, \Closure $next)
    {
        $controller = strtolower($request->controller());
        $action     = $request->action();

        $auth = $controller . '/' . $action;
        //要验证的请求
        $auth_urls = [
            'user/register_tk',
            'user/bind_phone',
            'user/info',
            'user/invite',
            'user/submit_withdrawal',
            'user/withdrawal_record',
            'user/orders',
            'user/income',
            'goods/info',
            'goods/collection',
            'goods/collection_action',
            'goods/cancel_collection',
            'goods/create_share_text',
            'goods/create_promotion_link',
            'goods/create_link',
            'goods/create_qrcode',
            'feed/info',
            'live/info',
            'live/qrcode',
        ];

        if (in_array($auth, $auth_urls)) {
            try {
                JWTAuth::auth();//token验证
            } catch (\Exception $e) {
                return $this->callback(ApiConstant::NO_LOGIN, 'token已失效');
            }
        }

        return $next($request);
    }
}
